package com.kuhh.listener;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.kuhh.service.ILoginHistoryService;
import com.kuhh.service.impl.LoginHistoryServiceImpl;


//监听器
@WebListener
public class CustomServerListener implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener{
	
	//上下文初始化，记录当前时间的时间戳，初始化人数统计变量
	private volatile ServletContext application = null;

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("------管理系统项目开始关闭------");
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("------管理系统项目初始化开始------");
		int onlineNum = 0;
		ILoginHistoryService visits = new LoginHistoryServiceImpl();
		visits.addVisits();
		application = sce.getServletContext();
		application.setAttribute("onlineNum", onlineNum);
		application.setAttribute("startTime", System.currentTimeMillis());
		application.setAttribute("visits", visits.getVisits());
	}
	
	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		System.out.println("------管理系统项目有人登录了------");
		int onlineNum = (int) application.getAttribute("onlineNum");
		application.setAttribute("onlineNum", ++onlineNum);
	}
	
	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		System.out.println("------管理系统项目有人退出了------");
		int onlineNum = (int) application.getAttribute("onlineNum");
		application.setAttribute("onlineNum", --onlineNum);
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		
	}
}
